package com.tanhua.service;

import com.huanxin.HuanxinTemplate;
import com.tanhua.domain.User;
import com.tanhua.dubbo.UserAPI;
import com.tanhua.util.JWTUtil;
import com.tanhua.vo.CodeVo;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    //注入远程调用
    @DubboReference
    private UserAPI userAPI;

    @Autowired
    private HuanxinTemplate huanxinTemplate;

    public Map loginVerification(CodeVo codeVo) {
        //根据手机号码远程查找用户信息
        User dbUser = userAPI.findByMobile(codeVo.getPhone());
        //如果找到了，表明是老用户，生成token，
        if (dbUser!=null){
            String token = JWTUtil.createToken(dbUser.getId(), dbUser.getMobile(), "tanhua", 300000);
            HashMap<String, Object> map = new HashMap<>();
            System.out.println("登录成功");
            map.put("token",token);
            map.put("isNew",false);
            return map;
        }
        //如果没有找到，表明是新用户，新用户....
        /**
         * 将用户保存到数据表tb_user
         * 远程调用userAPI，执行save方法，同时再将这个新增的用户返回
         */
        User newUser = new User();
        newUser.setMobile(codeVo.getPhone());
        User newDBUser = userAPI.save(newUser);

        newDBUser.setHxUser("hx"+newDBUser.getId());
        newDBUser.setHxPassword("123456");
        //借助环信templage保存到环信
        huanxinTemplate.createUser(newDBUser.getHxUser(),newDBUser.getHxPassword());
        //更新user表的两个字段
        userAPI.update(newDBUser);

        String token = JWTUtil.createToken(newDBUser.getId(), newDBUser.getMobile(), "tanhua", 300000);
        HashMap<String, Object> map = new HashMap<>();
        System.out.println("新用户注册成功");
        map.put("token",token);
        map.put("isNew",true);
        return map;


    }
}
